<template>
  <div class="admin-categories-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-title">
            <h1>📁 分类管理</h1>
            <p>管理系统中的帖子分类，组织内容结构</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总分类数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索分类名称..."
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 当前筛选条件 -->
    <div v-if="hasActiveFilters" class="filter-status">
      <div class="filter-status-header">
        <span class="filter-status-title">当前筛选条件</span>
        <el-button type="danger" plain size="small" @click="resetFilters">
          <el-icon><Close /></el-icon>
          清除所有筛选
        </el-button>
      </div>
      <div class="filter-tags">
        <el-tag
          v-if="filters.keyword"
          type="primary"
          closable
          @close="
            filters.keyword = '';
            handleSearch();
          "
        >
          关键词: {{ filters.keyword }}
        </el-tag>
        <el-tag
          v-if="filters.status !== ''"
          type="warning"
          closable
          @close="
            filters.status = '';
            handleSearch();
          "
        >
          状态: {{ getStatusName(filters.status) }}
        </el-tag>
      </div>
    </div>

    <!-- 分类列表 -->
    <el-card class="categories-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>分类列表 (共 {{ total }} 条)</span>
          <div class="header-actions">
            <el-button type="primary" @click="openCreateDialog" size="small">
              <el-icon><Plus /></el-icon>
              添加分类
            </el-button>
            <el-button type="primary" @click="loadCategories" :loading="loading" size="small">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="categories"
        stripe
        @sort-change="handleSortChange"
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />

        <el-table-column prop="name" label="分类名称" min-width="150">
          <template #default="{ row }">
            <div class="category-name">
              <span class="name">{{ row.name }}</span>
              <el-tag v-if="row.status === 0" type="danger" size="small" style="margin-left: 8px">
                已禁用
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="{ row }">
            <span class="description">{{ row.description || "-" }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="postCount" label="帖子数量" width="100" sortable>
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.postCount || 0 }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sortOrder" label="排序" width="80" sortable />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="toggleCategoryStatus(row)"
            />
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="openEditDialog(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="deleteCategory(row)"
              :disabled="row.postCount > 0"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 创建/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑分类' : '添加分类'"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="categoryForm.sortOrder"
            :min="0"
            :max="999"
            placeholder="排序值"
            style="width: 100%"
          />
          <div class="form-tip">数值越小排序越靠前</div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEditing ? "更新" : "创建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, watch } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { Search, Refresh, Plus, Edit, Delete, Close } from "@element-plus/icons-vue";
import {
  getAdminCategories,
  createAdminCategory,
  updateAdminCategory,
  deleteAdminCategory,
} from "@/api/admin";

// 接口定义
interface Category {
  id: number;
  name: string;
  description?: string;
  parentId?: number;
  sortOrder: number;
  status: number;
  createTime: string;
  updateTime: string;
  postCount: number;
}

// 响应式数据
const loading = ref(false);
const categories = ref<Category[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 筛选条件
const filters = reactive({
  keyword: "",
  status: "" as string | number,
});

// 对话框相关
const dialogVisible = ref(false);
const isEditing = ref(false);
const submitting = ref(false);
const categoryFormRef = ref<FormInstance>();

// 表单数据
const categoryForm = reactive({
  id: 0,
  name: "",
  description: "",
  sortOrder: 0,
  status: 1,
});

// 表单验证规则
const categoryRules: FormRules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 1, max: 50, message: "分类名称长度在 1 到 50 个字符", trigger: "blur" },
  ],
  description: [{ max: 200, message: "描述不能超过 200 个字符", trigger: "blur" }],
  sortOrder: [
    { required: true, message: "请输入排序值", trigger: "blur" },
    { type: "number", min: 0, max: 999, message: "排序值在 0-999 之间", trigger: "blur" },
  ],
};

// 原始分类数据
const allCategories = ref<Category[]>([]);

// 加载分类列表
const loadCategories = async () => {
  loading.value = true;
  try {
    const response = await getAdminCategories();

    // 处理响应数据
    if (Array.isArray(response)) {
      allCategories.value = response;
      filterCategories();
    } else {
      allCategories.value = [];
      categories.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("Failed to load categories:", error);
    ElMessage.error("加载分类列表失败");
    allCategories.value = [];
    categories.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 筛选分类
const filterCategories = () => {
  let filteredCategories = [...allCategories.value];

  // 按关键词筛选
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase();
    filteredCategories = filteredCategories.filter(
      category =>
        category.name.toLowerCase().includes(keyword) ||
        (category.description && category.description.toLowerCase().includes(keyword))
    );
  }

  // 按状态筛选
  if (filters.status !== "") {
    filteredCategories = filteredCategories.filter(
      category => category.status === Number(filters.status)
    );
  }

  // 应用分页
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  categories.value = filteredCategories.slice(startIndex, endIndex);
  total.value = filteredCategories.length;
};

// 搜索分类
const handleSearch = () => {
  currentPage.value = 1;
  filterCategories();
};

// 重置筛选
const resetFilters = () => {
  filters.keyword = "";
  filters.status = "";
  filterCategories();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  filterCategories();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  filterCategories();
};

// 排序处理
const handleSortChange = (sortData: { prop: string; order: string | null }) => {
  console.log("排序变化:", sortData);
  // 这里可以根据需要实现排序逻辑
};

// 打开创建对话框
const openCreateDialog = () => {
  isEditing.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (category: Category) => {
  isEditing.value = true;
  categoryForm.id = category.id;
  categoryForm.name = category.name;
  categoryForm.description = category.description || "";
  categoryForm.sortOrder = category.sortOrder;
  categoryForm.status = category.status;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  categoryForm.id = 0;
  categoryForm.name = "";
  categoryForm.description = "";
  categoryForm.sortOrder = 0;
  categoryForm.status = 1;

  nextTick(() => {
    categoryFormRef.value?.clearValidate();
  });
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const handleSubmit = async () => {
  if (!categoryFormRef.value) return;

  try {
    await categoryFormRef.value.validate();

    submitting.value = true;

    if (isEditing.value) {
      // 更新分类
      await updateAdminCategory(categoryForm.id, {
        name: categoryForm.name,
        description: categoryForm.description,
        sortOrder: categoryForm.sortOrder,
        status: categoryForm.status,
      });
      ElMessage.success("分类更新成功");
    } else {
      // 创建分类
      await createAdminCategory({
        name: categoryForm.name,
        description: categoryForm.description,
        sortOrder: categoryForm.sortOrder,
      });
      ElMessage.success("分类创建成功");
    }

    handleDialogClose();
    await loadCategories();
  } catch (error) {
    console.error("Submit error:", error);
    ElMessage.error(isEditing.value ? "分类更新失败" : "分类创建失败");
  } finally {
    submitting.value = false;
  }
};

// 切换分类状态
const toggleCategoryStatus = async (category: Category) => {
  try {
    await updateAdminCategory(category.id, {
      status: category.status,
    });
    ElMessage.success(`分类已${category.status === 1 ? "启用" : "禁用"}`);
    // 重新加载数据以确保状态同步
    await loadCategories();
  } catch (error) {
    console.error("Toggle status error:", error);
    // 恢复状态
    category.status = category.status === 1 ? 0 : 1;
    ElMessage.error("状态切换失败");
  }
};

// 删除分类
const deleteCategory = async (category: Category) => {
  if (category.postCount > 0) {
    ElMessage.warning("该分类下还有帖子，无法删除");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除分类"${category.name}"吗？删除后无法恢复。`, "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
    });

    await deleteAdminCategory(category.id);
    ElMessage.success("分类删除成功");
    await loadCategories();
  } catch (error) {
    if (error !== "cancel") {
      console.error("Delete error:", error);
      ElMessage.error("分类删除失败");
    }
  }
};

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString("zh-CN");
};

// 检查是否有活动筛选
const hasActiveFilters = computed(() => {
  return !!(filters.keyword || filters.status !== "");
});

// 获取状态名称
const getStatusName = (status: string | number) => {
  if (status === 1) {
    return "启用";
  } else if (status === 0) {
    return "禁用";
  }
  return "未知状态";
};

// 监听筛选条件变化
watch(
  () => [filters.keyword, filters.status],
  () => {
    // 筛选条件变化时重置到第一页并重新筛选
    currentPage.value = 1;
    filterCategories();
  },
  { deep: true }
);

// 组件挂载
onMounted(() => {
  loadCategories();
});
</script>

<style scoped lang="scss">
.admin-categories-view {
  .page-header {
    margin-bottom: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 24px;
    border-radius: 8px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .header-left {
      .header-title {
        h1 {
          margin: 0 0 8px 0;
          font-size: 28px;
          font-weight: 600;
        }

        p {
          margin: 0;
          opacity: 0.9;
          font-size: 14px;
        }
      }
    }

    .header-stats {
      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 32px;
          font-weight: bold;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
          margin-top: 4px;
        }
      }
    }
  }

  .filter-status {
    margin-bottom: 24px;
    padding: 16px 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;

    .filter-status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .filter-status-title {
        font-weight: 600;
        color: #495057;
        font-size: 14px;
      }
    }

    .filter-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .el-tag {
        border-radius: 4px;
        font-size: 12px;
      }
    }
  }

  .filter-card {
    margin-bottom: 24px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .filter-form {
      margin-bottom: 0;
    }
  }

  .categories-card {
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #2c3e50;

      .header-actions {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }

    .category-name {
      display: flex;
      align-items: center;

      .name {
        font-weight: 500;
        color: #2c3e50;
      }
    }

    .description {
      color: #666;
      font-size: 13px;
    }

    .pagination-wrapper {
      padding: 20px;
      text-align: center;
      border-top: 1px solid #ebeef5;
    }
  }

  .dialog-footer {
    text-align: center;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .admin-categories-view {
    .page-header {
      .header-content {
        flex-direction: column;
        gap: 16px;
      }
    }

    .filter-card {
      :deep(.el-form) {
        .el-form-item {
          margin-bottom: 12px;
          margin-right: 0;

          .el-form-item__content {
            flex-wrap: wrap;
          }
        }
      }
    }

    .categories-card {
      .card-header {
        flex-direction: column;
        gap: 12px;

        .header-actions {
          width: 100%;
          justify-content: flex-start;
        }
      }
    }
  }
}
</style>
